<template>
  <div class="shopping-cart">
    <h2>商品列表</h2>
    <div class="product-list">
      <div v-for="fruit in fruits" :key="fruit.id" class="product-item">
        <h3>{{ fruit.name }}</h3>
        <p>价格: ¥{{ fruit.price }}</p>
        <input 
          type="number" 
          v-model.number="fruit.quantity" 
          min="1" 
          @change="updateQuantity(fruit)"
        />
        <button @click="addToCart(fruit)">加入购物车</button>
      </div>
    </div>
    
    <h2>购物车</h2>
    <div v-if="cartItems.length > 0">
      <div v-for="item in cartItems" :key="item.id" class="cart-item">
        <span>{{ item.name }} × {{ item.quantity }}</span>
        <span>¥{{ item.price * item.quantity }}</span>
        <button @click="removeFromCart(item.id)">移除</button>
      </div>
      <div class="cart-total">
        <strong>总计: ¥{{ cartTotal }}</strong>
      </div>
    </div>
    <div v-else>
      <p>购物车为空</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ShoppingCart',
  computed: {
    fruits() {
      return this.$store.state.fruits.map(fruit => ({
        ...fruit,
        quantity: 1
      }));
    },
    cartItems() {
      return this.$store.getters.cartItems;
    },
    cartTotal() {
      return this.$store.getters.cartTotal;
    }
  },
  methods: {
    addToCart(fruit) {
      this.$store.dispatch('addToCart', {
        id: fruit.id,
        quantity: fruit.quantity
      });
    },
    removeFromCart(id) {
      this.$store.dispatch('removeFromCart', id);
    },
    updateQuantity(fruit) {
      this.$store.dispatch('updateQuantity', {
        id: fruit.id,
        quantity: fruit.quantity
      });
    }
  }
};
</script>

<style scoped>
.shopping-cart {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}
.product-item, .cart-item {
  border: 1px solid #ddd;
  padding: 15px;
  border-radius: 5px;
}
.cart-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.cart-total {
  text-align: right;
  margin-top: 20px;
  font-size: 1.2em;
}
button {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 3px;
  cursor: pointer;
}
button:hover {
  background-color: #369f6d;
}
input {
  width: 50px;
  margin-right: 10px;
}
</style>